package strts.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class StrutsParseXml {

	/**
	 * xml配置文件转化成类对象
	 * @param xmlPath xml配置文件路径
	 * @return
	 * @throws Exception
	 */
	public static Map<String, XmlBean> ParseXml(String xmlPath) throws Exception{
		Map<String,XmlBean> map = new HashMap<String,XmlBean>();
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Element actionmap = root.getChild("action-mapping");
		List<Element>  action = actionmap.getChildren();
		
		for(Element e:action){
			XmlBean xb = new XmlBean();
			String name = e.getAttributeValue("name");
			xb.setBeanName(name);
			Element formBean = root.getChild("formbeans");
			List<Element>  bean = formBean.getChildren();
			for(Element eb:bean){
				if(name.equals(eb.getAttributeValue("name"))){
					String beanClass=eb.getAttributeValue("value");
					xb.setBeanClass(beanClass);
				}

			}
			String path = e.getAttributeValue("path");
			xb.setPath(path);
			String type = e.getAttributeValue("type");
			xb.setActionType(type);
			List<Element>  forward = e.getChildren();
			Map<String,String>  fmap = new HashMap<String,String>();
			for(Element f:forward){

				String fname = f.getAttributeValue("name");
				String fvalue = f.getAttributeValue("value");
				fmap.put(fname,fvalue);

			}
			xb.setActionForward(fmap);
			map.put(path,xb);
		}

		return map;
	}
}
